shell 练习-实现一个小型计算器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
[root@nfs01 scripts]# cat bc.sh
#!/bin/sh
# First we should save the number which was inserted by user
read -p "Please insert the first number and the method you want to caculate:" num1
read -p "Please insert the second number and the method you want to caculate:" num2
read -p "Please insert the method you want to caculate:" \opt
usage(){
echo "Usage $0 num1 num2 operation"
exit 1
}
if_int(){
num=$1
if [ ! -z $(echo $num | sed 's/[0-9]//g') ];then
usage
exit 2
fi
}
if_int $num1
if_int $num2
caculate(){
echo "${num1}${opt}${num2}=$((${num1}${opt}${num2}))"
}
if_zero(){
if [ $1 -eq 0 ];then
echo "The dividend can't be zero,please input a number which is not equal 0"
exit 3
fi
}
case $opt in
"+")
caculate $num1 $num2 $opt
;;
"-")
caculate $num1 $num2 $opt
;;
"*")
caculate $num1 $num2 $opt
;;
"/")
if_zero $num2
result=$(echo ${num1}${opt}${num2} | bc )
echo $result
;;
"%")
caculate $num1 $num2 $opt
;;
esac

        这个试题遇到的问题就是尽量不要进行变量的复用,变量的多次复用会导致意外的问题。比如从用户那里接受到了 $opt=* ,然后当把变量再赋值给另外的变量的时候那就不是 了,这个 会被解析成为当前目录下的所有文件,就会出问题,除非要求用户输入的时候指定 \* 这种格式,给 * 脱意。